import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '../store/store';
import router from '../router/router.js'

const api = axios.create({
    baseURL: '/api',
    timeout: 600000,
})


api.interceptors.request.use(
    config => {
        store.commit('setLoading', true)
        if (localStorage.getItem('token')) {
            let token = localStorage.getItem('token')
            config.headers.set('token', token)
        }
        return config;
    }
)


api.interceptors.response.use(
    response => {
        store.commit('setLoading', false)
        if(response.status) {
            return Promise.resolve(response)
        } else {
            return Promise.reject(response)
        }
    },
    error => {
        store.commit('setLoading', false)
        console.log(error.response)
        if (error.response.status) {
            switch (error.response.status) {
                case 400:
                    ElMessage({
                        message: error.response.data.msg,
                        type: 'error'
                    })
                    if (error.response.data.code === 100001) {
                        router.replace({name: 'Hall'})
                    }
                    break;
                case 401:
                    ElMessage({
                        message: '身份过期',
                        type: 'error'
                    })
                    localStorage.removeItem('token')
                    router.replace({name: 'Hall'})
                    break;
                default:
                    break;
            }
        }
        return Promise.reject(error);
    }
)


export default api

